package com.feng.cloud.gateway.configure;

import com.feng.cloud.gateway.handler.GatewayExceptionHandler;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.List;

/**
 * @ClassName GatewayErrorConfigure
 * @Description 网关异常类配置
 * @Author Better Feng
 * @Date 2019/12/16 11:43
 * @Version 1.0
 **/
@Configuration
@AllArgsConstructor
public class GatewayErrorConfigure {

    private final ServerProperties serverProperties;
    private final ApplicationContext applicationContext;
    private final ResourceProperties resourceProperties;
    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
        GatewayExceptionHandler gatewayExceptionHandler = new GatewayExceptionHandler(
                errorAttributes,this.resourceProperties,this.serverProperties.getError(),
                this.applicationContext);
        gatewayExceptionHandler.setViewResolvers(this.viewResolvers);
        gatewayExceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
        gatewayExceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
        return gatewayExceptionHandler;
    }

}
